// 描述：与业务相关的 api

(function (E, KIT, RES) {

    RES.URL_FORM_DESIGNER_ROOT = RES.URL_ROOT + "/formdesigner";
    RES.URL_FIND_FORM_DATASOURCE = RES.URL_FORM_DESIGNER_ROOT + "/findDataSource";

    RES.URL_CHARGE_MANAGE_ROOT = RES.URL_ROOT + "/chargemanage";

    KIT.loadAdminResourceSync(RES.URL_API + "/loadResource");

    RES.FORM_DEFAULT_VAL = [{
        text: "企业名称", value: "USER_NAME"
    }, {
        text: "统一信用代码", value: "CARD_ID"
    }, {
        text: "联系人", value: "CONTACTS"
    }, {
        text: "联系电话", value: "USER_PHONE"
    }];

    KIT.setAreaUI = function (app, pkSf, pkCs, pkQx) {
        var __sf = rapid.nvl(app.tag("sf"), null),
            __cs = rapid.nvl(app.tag("cs"), null),
            __qx = rapid.nvl(app.tag("qx"), null);

        if (rapid.isEmpty(__sf)) {
            pkSf.load({
                data: null
            }).disabled(false);

            pkCs.disabled(true);
            pkQx.disabled(true);

        } else {
            pkSf.text(__sf.text).value(__sf.value).readonly(true);

            if (rapid.hasValue(__cs)) {
                pkCs.text(__cs.text).value(__cs.value).readonly(true);

                if (rapid.hasValue(__qx)) {
                    pkCs.text(__qx.text).value(__qx.value).readonly(true);

                } else {
                    pkQx.load({
                        data: "pcode=" + __cs.value
                    }).disabled(false);
                }

            } else {
                pkCs.load({
                    data: "pcode=" + __sf.value
                }).disabled(false);

                pkQx.disabled(true);
            }
        }
    };

    KIT.getDisabledText = function (text) {
        return E.view({cssClass: "r-italic r-p-r-xs"},
            E.text({cssClass: "r-cl-12-5"}, text) +
            " (" + E.text({cssClass: "r-cl-7-7"}, "已禁用") + ")"
        );
    };

    KIT.setDisabledFieldCss = function (css) {
        css.color = 8;
        css.depth = 2;
        css.italic = true;
    };

    /**
     * jQuery (menglingbin)
     * 解析由数据库保存的表单字段结构，将其转换为dataview参数
     * @param field
     */
    KIT.formFieldFactroy = function (field, isSearch) {

        var _item = {};

        _item.editor = {};

        var _editor = {};

        _editor.type = field.type;

        //region 基础属性

        if (!isSearch) {
            _item.title = field.title;
            if(field.is_editor!=null && field.is_editor=="0"){
                _editor=false;
            }
        } else {

            _editor.tip = field.title;
        }
        //_item.align = "center";

        if (!rapid.isEmpty(field.controller_id)) {
            _item.id = field.controller_id;
        }

        if (!rapid.isEmpty(field.col_span)) {
            _item.size = field.col_span != 12 ? 0 : 12;
        }

        if (!rapid.isEmpty(field.grid_field_visible) && field.grid_field_visible) {
            _item.visible = false;
        }

        if (!rapid.isEmpty(field.grid_show_name)) {
            _item.name = field.grid_show_name;
            _editor.name = field.field.toLowerCase();
            _editor.textField = field.grid_show_name;
        } else {
            _item.name = field.field.toLowerCase();
            _editor.name = field.field.toLowerCase();
        }

        if (!rapid.isEmpty(field.gird_field_width)) {
            _item.width = field.gird_field_width;
        }

        if (!rapid.isEmpty(field.default_value)) {
            _editor.defaultValue = RES[field.default_value];
        }

        //endregion

        //region设置验证器

        var _rules = {};

        if (!isSearch) {

            //必填
            if (field.required == 1) {
                _rules.required = true;
            }

            //数字最大值
            if (!rapid.isEmpty(field.number_max_value)) {
                _rules.max = field.number_max_value;
            }

            //数字最小值
            if (!rapid.isEmpty(field.number_min_value)) {
                _rules.min = field.number_min_value;
            }

            //字符串最大长度
            if (!rapid.isEmpty(field.string_max_length)) {
                _rules.maxlength = field.string_max_length;
            }

            //数字输入框-整型
            if (field.type == "numberbox") {
                _rules.integer = true;
                delete _editor.type;
            }

            //带小数的输入框
            if (field.type == "digitbox") {
                _rules.numeric = true;
                delete _editor.type;
            }

            //验证手机号码
            if (field.type == "textbox" && field.validator_type == "mobileno") {
                _rules.mobileno = true;
            }
            //验证邮箱
            if (field.type == "textbox" && field.validator_type == "email") {
                _rules.email = true;
            }
            //验证邮政编码
            if (field.type == "textbox" && field.validator_type == "postalcode") {
                _rules.postalcode = true;
            }
            //验证身份证号码
            if (field.type == "textbox" && field.validator_type == "idcard") {
                _rules.idcard = true;
            }
            //正能是大小写英文
            if (field.type == "textbox" && field.validator_type == "letter") {
                _rules.letter = true;
            }
            //验证网址
            if (field.type == "textbox" && field.validator_type == "url") {
                _rules.url = true;
            }
            //验证固定电话
            if (field.type == "textbox" && field.validator_type == "phoneno") {
                _rules.phoneno = true;
            }

            if (!rapid.isEmpty(_rules)) {
                _item.editor = $.extend(true, {}, _item.editor, {validator: {rules: _rules}});
            }
        }
        //endregion

        //控件绑定数据
        var _textField = "codename";
        var _valueField = "customid";
        var _url = RES.URL_API + "/getCodesByCodeTypeAndLeaf";
        var _data = {
            codetype: field.code_type,
            leaf: field.code_leaf
        };

        if (field.type == "picker" || field.type == "pickermultiple" || field.type == "pickeredit" || field.type == "pickermultipleedit") {

            _editor.type = "picker";

            _editor.autoReload = true;
            _editor.tip = "请选择...";

            if (!rapid.isEmpty(field.custom_data_url)) {
                _textField = "text";
                _valueField = "value";
                _url = field.custom_data_url;
                if(field.custom_data_url == "/sysadmin/api/query"){

                    _url = _url + "?param=" + field.custom_data_option
                }else{

                    if (!rapid.isEmpty(field.custom_data_option)) {
                        _data = eval('(' + field.custom_data_option + ')');
                    } else {
                        _data = null;
                    }
                }
            }

            _editor.dataSource = {
                textField: _textField,
                valueField: _valueField,
                url: _url,
                data: _data
            };


            if(rapid.parseUrl().params.code=='rjxmpg' ) {
                if (field.field == 'ATTRIB_33') {
                    _editor.onchange = function (e) {


                        rapid.post({
                            url: "/sysadmin/formdata/getGdd",
                            data: {
                                vals: e.ui("attrib_33").text()
                            },
                            success: function (r) {

                                if(rapid.isEmpty(r))
                                    e.ui("attrib_32").val("0");
                                    else
                                    e.ui("attrib_32").val(r);
                            }
                        });
                    }

                }

                if (field.field == 'ATTRIB_34') {
                    _editor.onchange = function (e) {

                        rapid.post({
                            url: "/sysadmin/formdata/getKfyy",
                            data: {
                                vals:  e.ui("attrib_34").val()
                            },
                            success: function(r) {

                                if(rapid.isEmpty(r))
                                    e.ui("attrib_08").text("0");
                                else
                                    e.ui("attrib_08").val(r);
                            }
                        });
                    }

                }
                if (field.field == 'ATTRIB_07') {
                    _editor.onchange = function (e) {

                        rapid.post({
                            url: "/sysadmin/formdata/getJsms",
                            data: {
                                vals:  e.ui("attrib_07").text()
                            },
                            success: function(r) {
                                if(rapid.isEmpty(r))
                                    e.ui("attrib_10").val("0");
                                else
                                    e.ui("attrib_10").val(r);
                            }
                        });
                    }

                }
                if (field.field == 'ATTRIB_35') {
                    _editor.onchange = function (e) {

                        rapid.post({
                            url: "/sysadmin/formdata/getBfyh",
                            data: {
                                vals:  e.ui("attrib_35").text()
                            },
                            success: function(r) {
                                if(rapid.isEmpty(r))
                                    e.ui("attrib_09").val("0");
                                else
                                    e.ui("attrib_09").val(r);
                            }
                        });
                    }

                }
                if (field.field == 'ATTRIB_31') {
                    _editor.onchange = function (e) {

                        rapid.post({
                            url: "/sysadmin/formdata/getHy",
                            data: {
                                vals:  e.ui("attrib_31").text()
                            },
                            success: function(r) {
                                if(rapid.isEmpty(r))
                                    e.ui("attrib_36").val("0");
                                else
                                    e.ui("attrib_36").val(r);
                            }
                        });
                    }

                }
            }
            //数据级联
            if (field.is_cascade == "1") {

                if (field.code_leaf == "2") {
                    _editor.defaultValue = "请选择"
                    _editor.defaultText = "江苏省",
                        _editor.onchange = function (dv) {

                            var __fields = field.cascade_field.toLowerCase();
                            var __value = this.val(),
                                __pk1 = dv.ui(__fields).reset();

                            if (rapid.isEmpty(__value)) {
                                __pk1.disabled(true);

                            } else {
                                __pk1.dataSource({
                                    data: {
                                        codetype: field.code_type,
                                        leaf: 3,
                                        pcode: __value
                                    }
                                }).disabled(false);
                            }
                        }
                }

                if (field.code_leaf == "3") {

                    //_editor.disabled = true;
                    _editor.onchange = function (dv) {

                        var __fields = field.cascade_field.toLowerCase();
                        var __value = this.val(),
                            __pk1 = dv.ui(__fields).reset();

                        if (rapid.isEmpty(__value)) {
                            __pk1.disabled(true);

                        } else {
                            __pk1.dataSource({
                                data: {
                                    codetype: field.code_type,
                                    leaf: 4,
                                    pcode: __value
                                }
                            }).disabled(false);
                        }
                    }
                }

                if (field.code_leaf == "4") {

                    _editor.disabled = true;
                }
            }

            if (field.type == "pickermultiple" || field.type == "pickermultipleedit") {
                _editor.multiple = true;   //多选
            }

            //模糊匹配
            if (field.type == "pickeredit" || field.type == "pickermultipleedit") {
                _editor.editable = true;   //可编辑的
                _editor.autocomplete = {
                    dataSource: {
                        textField: _textField,
                        valueField: _valueField,
                        url: _url,
                        data: function (v) {
                            var _op = {searchname: v};
                            if (!rapid.isEmpty(_data)) {
                                _op = $.extend(true, {}, _op, _data);
                            }
                            return _op;
                        }
                    }
                };
            }
        }

        if (field.type === "checkboxlist" || field.type === "radiolist") {
            if (!rapid.isEmpty(field.custom_data_url)) {
                _textField = "text";
                _valueField = "value";
                _url = field.custom_data_url;
                if (!rapid.isEmpty(field.custom_data_option)) {
                    _data = eval('(' + field.custom_data_option + ')');
                } else {
                    _data = null;
                }
            }

            _editor.dataSource = {
                textField: "codename",
                valueField: "customid",
                url: _url,
                data: _data
            };
        }

        if (field.type == "datetimepicker") {
            _item.align = "center";
            _editor.type = "datetimepicker";
            _editor.mode = "yMdhm";
            _editor.valueFormatter = "yyyy-MM-dd hh:mm:ss";
            _editor.textFormatter = "yyyy-MM-dd hh:mm";
            _item.formatter = function (value, css) {
                if (!rapid.str.isEmpty(value)) {
                    return rapid.date.format(value, "yyyy-MM-dd hh:mm");
                }
                return "";
            }
        }

        if (field.type == "datepicker") {
            _item.align = "center";
            _editor.type = "datetimepicker";
            _editor.mode = "date";
            _item.formatter = function (value, css) {
                if (!rapid.str.isEmpty(value)) {
                    return rapid.date.removeTime(value);
                }
                return "";

            }
        }

        if (field.type == "timepicker") {
            _item.align = "center";
            _editor.type = "datetimepicker";
            _editor.mode = "hm";
            _editor.valueFormatter = "yyyy-MM-dd hh:mm:ss";
            _editor.textFormatter = "hh:mm";
            _item.formatter = function (value, css) {
                if (!rapid.str.isEmpty(value)) {
                    return rapid.date.format(value, "hh:mm");
                }
                return "";
            }
        }

        if (field.type == "switchbutton") {
            _item.align = "center";
            _editor.type = "checkbox";
            _editor.mode = "switch";
            _editor.checked = true;
            _editor.text = ["是", "否"];
            _editor.value = [1, 0];
            _item.formatter = function (value, css) {
                var __text = "";
                if (value == 1) {
                    css.color = 1;
                    __text = "是";
                } else {
                    __text = "否";
                }
                return __text;
            }
        }

        if (field.type == "wangeditor") {
            _item.size = 12;
            _editor = KIT.tmplWangEditor({
                name: _editor.name
            });

        }

        if (field.type == "textarea") {

            _item.size = 12;
            _editor = KIT.tmplTextArea({
                name: _editor.name
            });

        }

        if (field.type == "download") {

            _item.action = function (row, css) {

                if (!rapid.isEmpty(row[field.field.toLowerCase()])) {
                    return this.action({id: "download_" + field.field.toLowerCase(), text: "预览下载", color: 1});
                }
            };
            _item.name = null;
            _editor = false;
        }

        var files = [];
        if (field.type == "webuploader") {
            _item.size = 12;
            _item.visible = false;
            _editor = KIT.tmpWebuploader({
                id: rapid.id("webupload"),
                uploadType: "file",
                accept: {
                    title: 'File',
                    //  extensions: 'xls,XLS,xlsx,XLSX,zip,docx,pdf,doc,pptx,mp4,',
                    mimeTypes: 'application/xls,application/xlsx'+',image/*,text/*,image/bmp'
                        //word
                        +',application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        //excel
                        +',application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        //ppt
                        +',application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation'
                        +',application/pdf'
                        +',application/zip'
                        +',application/csv' +',application/cad,video/*,image/*'

                },
                name: _editor.name,
                ratio: 1.2,
                multiple: false,
                fileNumLimit: 20,
                threads: 20,
                hideFileName: true,
                server: "/comm/api/webUpload",
                onUploadSuccess: function (file, response) {

                    if (rapid.isUndefined(response)) {
                        rapid.warning("系统异常，请刷新。");
                        return false;
                    }
                    if (!rapid.isEmpty(response.message)) {
                        rapid.warning(response.message, true);
                    }
                    if (response.state == 1) {

                        var fileName = $(".webuploader-container").find("input[name='file']").val();
                        if (rapid.isEmpty(fileName) && fileName.length == 0) {

                            $("input[name='"+_editor.name+"']").remove();
                            var _html = "<input type='hidden' id='"+_editor.name+"' name='"+_editor.name+"' value='" + response.data + "'/>";

                            $(".uploader-list").append(_html);


                        }

                    }
                }
            });

        }

        //endregion

        if(_editor != false){
            _item.editor = $.extend(true, {}, _item.editor, _editor);
        }else{
            _item.editor = false;
        }

        return _item;
    };

})(rapid.html.Element, rapid.kit, rapid.res);
 